package cn.wolfcode.ssm.web.controller;

import cn.wolfcode.ssm.domain.Employee;
import cn.wolfcode.ssm.exception.LogicException;
import cn.wolfcode.ssm.qo.JsonResult;
import cn.wolfcode.ssm.service.IEmployeeService;
import cn.wolfcode.ssm.service.INoticeService;
import cn.wolfcode.ssm.service.IPermissionService;
import cn.wolfcode.ssm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IPermissionService permissionService;
    @Autowired
    private INoticeService noticeService;

    @RequestMapping("/userLogin")
    @ResponseBody
    public JsonResult login(String username, String password,JsonResult jsonResult){
            //根据数据库验证账号密码
        Employee employee = null;
        try {
            employee = employeeService.login(username, password);
        } catch (LogicException e) {

            Integer oldErrorTime = UserContext.getErrorTime();
            if(oldErrorTime == null){
                oldErrorTime = 1;
                UserContext.setErrorTime(oldErrorTime);
            }else {
                if(oldErrorTime<=5){
                    UserContext.setErrorTime(oldErrorTime+1);
                }else {
                    //锁定页面
                    
                }
            }

            int errorTime = 0;
        }
        //将用户信息存在Session中
            UserContext.setEmployee(employee);
            //获取该用户的权限信息（表达式）并存在Session中
            List<String> expressions = permissionService.selectForExpressionById(employee.getId());
            UserContext.setPermission(expressions);
            if(employee.getId()!=null){
                int count = noticeService.countNoRead(employee.getId());
                UserContext.getSession().setAttribute("COUNT_IN_SESSION",count);
            }


            return new JsonResult();

    }

    @RequestMapping("/userLogout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/login.html";
    }
}
